<template>
  <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="领料人" prop="userId">
                <el-select v-model="form.userId" placeholder="请选择领料人" filterable @change="selectUser" clearable>
                  <el-option v-for="dict in dict.type.sys_user" ref="myselectUser"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="锁定时间" prop="useDate">
                <el-date-picker clearable
                                v-model="form.useDate"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                placeholder="请选择锁定时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <div style="margin-left: 30px;">
              产品发货总数量：{{shuliang}}
            </div>
          </el-row>
      <el-table border v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" ref="table" :max-height="tableMaxHeight">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="供应商名称" align="center" prop="supplierName" show-overflow-tooltip/>
     <!--   <el-table-column label="入库批次号" align="center" prop="nos" show-overflow-tooltip/>-->
        <el-table-column label="销售订单号" align="center" prop="projectNo" show-overflow-tooltip/>
        <el-table-column label="产品编码" align="center" prop="code" show-overflow-tooltip/>
        <el-table-column label="单位" align="center" prop="unit"/>
        <el-table-column label="到货单号" align="center" prop="daohuono"/>
        <el-table-column label="入库日期" align="center" prop="rukudate" width="180"  show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.rukudate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入库人" align="center" prop="rukuren"/>
        <el-table-column label="入库批次编号" align="center" prop="rukuno"/>
        <el-table-column label="入库数量" align="center" prop="daohuoCount"/>
        <el-table-column label="是否自制" align="center" prop="isdo">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.isdo" :value="scope.row.isdo"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="剩余数量" prop="canCount"/>
        <el-table-column align="center" label="选用发货数量" width="210">
          <template slot-scope="scope">
            <el-input-number size="mini" v-model="scope.row.useCount"  :min="0" :max="maxValue(scope.row.canCount)"></el-input-number>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" v-if="">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList"/>
  </el-dialog>
</template>

<script>
  import { deleteAction, getAction,addAction } from '@/api/manage'
  //import LvRukumingxiForm from '@/views/develop/lvRukumingxi/module/LvRukumingxiForm'

  export default {
    name: "ChoseGoodsFahuoFormList",
    dicts: ['isdo','sys_user'],
    components: {
    },
    data() {
      return {
        shuliang:'', //发货总数量
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        title:"",
        open:false,
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 出入库记录表格数据
        dataList: [],
        counts:"",
        gsaleId:"",
        yifahuomingxiId:"",
        goodsUnit:"",
        dataListChose: [],
        rules: {},
        form: {
          userId: this.$store.getters.userId,
          userName: this.$store.getters.nickName,
          useDate: new Date(),
          goodsType: "1",
        },
        //goodsCount:"",
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 20,
          goodsId: null,
          goodsTotalPrice: null,
          goodsBuyPrice: null,
          goodsBuyTotal: null,
          goodsProfit: null,
          saleDate: null,
          supplierId: null,
          supplierName: null,
          customerId: null,
          customerName: null,
          saleId: null,
          saleName: null,
          projectId: null,
          projectName: null,
          status: "1",
          isfahuo: null,
          fahuoDate: null,
          code: null,
          dun: null,
          nos: null,
          isdo: null,
          canCount: null,
          mainId: null,
          qinggouId: null,
          caigouno: null,
          unit: null,
          daohuoId: null,
          zhijianDate: null,
          zhijianName: null,
          isZhijian: null,
          zhijiandan: null,
          daohuono: null,
          daohuodate: null,
          rukudate: null,
          rukuren: null,
          rukuno: null,
          daohuoCount: null,
          type: "0",
          orderByColumn: "daohuo_count",
          isAsc: "desc",
        },
        url: {
          list:'/lvRukumingxi/lvRukumingxi/list',
          remove:'/lvRukumingxi/lvRukumingxi/',
          export:'/lvRukumingxi/lvRukumingxi/export',
          submitGoodsSaleFahuo:'/goodsSaleMaterialDetail/goodsSaleMaterialDetail/submitGoodsSaleFahuo',
        },
        tableMaxHeight: window.innerHeight - 100,
      };
    },
    created() {
      //this.getList();
      window.addEventListener('resize', this.getTableHeight);
    },
    destroyed () {
      window.removeEventListener('resize', this.getTableHeight)
    },
    methods: {
      selectUser(value) {
        let that = this;
        that.$nextTick(() => {
          let arr = that.$refs.myselectUser;
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].currentValue == value) {
              that.form.userName = arr[i].label;
            }
          }
        })
      },
      maxValue(canCount){
        return Math.min(canCount, canCount);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        // this.reset();
      },
      /** 查询出入库记录列表 */
      getList() {
        this.loading = true;
        getAction(this.url.list, this.queryParams).then(response => {
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      getTableHeight () {
        this.tableHeight = window.innerHeight - 100
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
        this.dataListChose=selection;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.$refs.form.handleAdd();
      },
      /** 修改按钮操作 */
      showRukuGoods(row) {
        //this.counts=row.goodsCount;
        this.yifahuomingxiId=row.id;
        this.gsaleId=row.saleId;
        this.goodsUnit=row.unit;
        this.shuliang=row.shuliang;
        //this.reset();
        this.open = true;
        this.title = "选择锁定11产品";
        this.queryParams.goodsId=row.goodsId;
        this.getList();
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        deleteAction(this.url.remove, ids).then(response => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download(this.url.export, {
          ...this.queryParams
        }, `lvRukumingxi_${new Date().getTime()}.xlsx`)
      },
      /** 提交按钮 */
      submitForm() {
        let that = this;
        const ids = this.ids;
        if (ids == null || ids == '' || ids == 'undefined') {
          that.$modal.msgError("请选择一条记录");
        } else {
          // 校验选用发货数量的总和是否超过产品发货总数量
          const totalUseCount = this.dataListChose.reduce((sum, item) => sum + (item.useCount || 0), 0);
          if (totalUseCount > this.shuliang) {
            that.$modal.msgError("选用发货数量的总和不能超过产品发货总数量");
            return;
          }

          that.$refs["form"].validate(valid => {
            if (valid) {
              const dataFormList = Object.assign({});
              dataFormList.yifahuomingxiId = that.yifahuomingxiId;
              dataFormList.gsaleId = that.gsaleId;
              dataFormList.goodsUnit = that.goodsUnit;
              dataFormList.userId = that.form.userId;
              dataFormList.userName = that.form.userName;
              dataFormList.useDate = that.form.useDate;
              dataFormList.columns = that.dataListChose;
              addAction(that.url.submitGoodsSaleFahuo, dataFormList).then(response => {
                that.$modal.msgSuccess("添加成功");
                that.open = false;
                that.$emit('ok');
                that.getList();
                that.handleQuery();
              });
            }
          });
        }
      },
    }
  };
</script>
